#include "urlimagelabel.h"
#include <QMovie>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QPixmap>
#include<QImage>
#include<QDebug>
#include<QDir>
#include<QCryptographicHash>
QNetworkAccessManager* URLImageLabel::manager = new QNetworkAccessManager();
QString URLImageLabel::cachePath = "cache/";
QString URLImageLabel::imgPath = "http://fridge.binw.top:9000";
URLImageLabel::URLImageLabel(QWidget *parent):QLabel(parent)
{

}
void URLImageLabel::showURLImage(QString url){
    imgUrl = imgPath + url;
    //获取网络图片
    //返回哈希数据，第二个参数是采用何种算法
    QByteArray hashData = QCryptographicHash::hash(url.toLocal8Bit(),QCryptographicHash::Md5);
    //返回字节数组的十六进制编码，编码使用数字0-9和字母a-f
    fileName = hashData.toHex()+".jpg";
    QFileInfo fileInfo(cachePath + fileName);
    if(fileInfo.exists())
    {
        paint();
        return;
    }
    loading();
    connect(manager, &QNetworkAccessManager::finished,
        this, &URLImageLabel::replyFinished);
    manager->get(QNetworkRequest(QUrl(imgUrl)));
}

void URLImageLabel::replyFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        qDebug()<<reply->url().toString();
        if(reply->url().toString()==imgUrl)
        {
            QDir dir(cachePath);
            if(!dir.exists())
            {
                dir.mkpath(cachePath);
            }
            //获取字节流构造 QPixmap 对象
            QPixmap currentPicture;
            currentPicture.loadFromData(reply->readAll());
            QString currentFileName = cachePath + fileName;
            currentPicture.save(currentFileName);//保存图片
            //可以在onpaint中 用QPixmap 显示currentPicture，则这种方法则不需要保存
            QPixmap pixmap = currentPicture.scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            //Qt::IgnoreAspectRatio, Qt::SmoothTransformation);//设置图片大小和label的长宽一致
            setScaledContents(true);
            setPixmap(pixmap);
            reply->abort();
            reply->close();
            reply->deleteLater();
            manager->disconnect(this);
        }
    }
//    else{
//        failed();
//    }
}
void URLImageLabel::failed(){
    QMovie* movie = new QMovie(":/img/res/img/loadfailed.jpg");
    QSize si(width(),height());
    movie->setScaledSize(si);
    movie->start();
    setMovie(movie);
}
void URLImageLabel::loading(){
    QMovie* movie = new QMovie(":/img/res/img/loading.gif");
    QSize si(width(),height());
    movie->setScaledSize(si);
    movie->start();
    setMovie(movie);
}
void URLImageLabel::paint()
{
    QPixmap *pixmap = new QPixmap(cachePath+fileName);
    pixmap->scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    setScaledContents(true);
    setPixmap(*pixmap);
}
URLImageLabel::~URLImageLabel(){

}
